package com.vancouver.knows.ui.activity.my;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.FileUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.EditUserProfileTaskMark;
import com.vancouver.knows.business.task.mark.GetUserPostsTaskMark;
import com.vancouver.knows.business.task.mark.UserUploadImageTaskMark;
import com.vancouver.knows.ui.activity.userpost.UserPostSubcategoryListActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.citynews.Crop;
import com.vancouver.knows.ui.fragment.citynews.SelectPicWindow;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.CircleTransform;
import com.vancouver.knows.util.PhoConstants;

import java.io.File;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-07-22.
 */
public class EditProfileActivity extends BaseActivity implements IResultReceiver, View.OnClickListener {

    @Bind(R.id.user_image)
    ImageView mUserImage;
    @Bind(R.id.user_name_input)
    EditText mUsernameInput;
    @Bind(R.id.user_phone_input)
    EditText mPhoneInput;
    @Bind(R.id.user_email_input)
    EditText mEmailInput;
    @Bind(R.id.location_text)
    TextView mLocationText;

    private BSharedPrefManager mSharedPrefManager;
    private SelectPicWindow mSelectPicDialog;
    private SelectWindow mLogoutDialog;
    private String mLocalFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        mSelectPicDialog = new SelectPicWindow(this, this);
        mLogoutDialog = new SelectWindow(this, this, getString(R.string.sure_quit), getString(R.string.sure));

        mSharedPrefManager = imContext.getSharedPrefManager();

        setViews();
    }

    private void setViews() {

        if (mSharedPrefManager == null) {
            return;
        }
        UserInfo.UserMeta userMeta = mSharedPrefManager.getUserMeta();
        UserInfo.RegisterType registerType = mSharedPrefManager.getRegisterType();
        mUsernameInput.setHint(mSharedPrefManager.getUserName());
        if (userMeta != null) {
            mPhoneInput.setHint(userMeta.getPhone());
            mEmailInput.setHint(userMeta.getEmail());
            mLocationText.setText(userMeta.getCity());
            if (mUserImage.getDrawable() == null) {
                Picasso.with(this).load(userMeta.getAvatar()).transform(new CircleTransform()).fit().centerCrop().into(mUserImage);
            }
        }

        if (registerType != null) {
            if (registerType.getType().equals("phone")) {
                mPhoneInput.setText(registerType.getUserLogin());
                mPhoneInput.setFocusable(false);
                mPhoneInput.setInputType(InputType.TYPE_NULL);
            } else if (registerType.getType().equals("email")) {
                mEmailInput.setText(registerType.getUserLogin());
                mEmailInput.setFocusable(false);
                mEmailInput.setInputType(InputType.TYPE_NULL);
            }
        }
    }

    @OnClick(R.id.location_picker)
    public void onLocationPickerClicked() {
        Intent intent = new Intent(this, UserPostSubcategoryListActivity.class);
        intent.putExtra(UserPostSubcategoryListActivity.IS_CITY_CATEGORY_EXTRA, true);
        intent.putExtra(UserPostSubcategoryListActivity.SELECTED_CITY_DATA, mLocationText.getText().toString());
        startActivityForResult(intent, UserPostSubcategoryListActivity.CHOOSE_CITY_REQUEST);
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    @OnClick(R.id.save_icon)
    public void onSaveClicked() {
        String username = mUsernameInput.getText().toString().trim();
        if (StringUtil.isEmptyString(username)) {
            username = mUsernameInput.getHint().toString().trim();
        }

        String userId = mSharedPrefManager.getUserId();
        if (userId == null) {
            return;
        }

        String location = mLocationText.getText().toString().trim();
        if (StringUtil.isEmptyString(location)) {
            location = null;
        }

        if (mPhoneInput.isFocusable()) {
            String phone = mPhoneInput.getText().toString().trim();
            if (!StringUtil.isEmptyString(phone)) {
                if (!StringUtil.isValidPhoneNumber(phone)) {
                    Toast.makeText(this, R.string.invalid_phone_number, Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            imContext.getBusinessModule().getServiceWrapper().editUserProfile(this, new EditUserProfileTaskMark(), userId, username, null, phone, location);
        } else if (mEmailInput.isFocusable()) {
            String email = mEmailInput.getText().toString().trim();
            if (!StringUtil.isEmptyString(email)) {
                if (!StringUtil.isValidEmail(email)) {
                    Toast.makeText(this, R.string.invalid_email, Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            imContext.getBusinessModule().getServiceWrapper().editUserProfile(this, new EditUserProfileTaskMark(), userId, username, email, null, location);
        }
    }

    @OnClick(R.id.user_image)
    public void onUserImageClicked() {
        mSelectPicDialog.show();
    }

    @OnClick(R.id.logout_button)
    public void onLogoutButtonClicked() {
        mLogoutDialog.show();
    }

    private void setUserImgFromPhoto(File imgFile) {
        Picasso.with(this).load(imgFile).transform(new CircleTransform()).fit().into(mUserImage);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String userImageUrl = null;
        if (requestCode == Crop.REQUEST_PICK && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String path = AppUtils.createFile(this, uri, FileUtil.getSdcardStoreDir() + File.separator
                    + PhoConstants.ADD_POST_IMAGE_DIR + System.currentTimeMillis() + ".jpg");
            if (!StringUtil.isEmptyString(path)) {
                setUserImgFromPhoto(new File(path));
                userImageUrl = path;
            }

        } else if (requestCode == Crop.REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {
            setUserImgFromPhoto(new File(mLocalFilePath));
            userImageUrl = mLocalFilePath;
        } else if (requestCode == UserPostSubcategoryListActivity.CHOOSE_CITY_REQUEST && resultCode == Activity.RESULT_OK) {
            String selectedCity = data.getStringExtra(UserPostSubcategoryListActivity.SELECTED_CITY_DATA);
            mLocationText.setText(selectedCity);
        }

        if ((requestCode == Crop.REQUEST_PICK || requestCode == Crop.REQUEST_CAMERA) && resultCode == Activity.RESULT_OK) {
            if (userImageUrl != null && userImageUrl.length() > 0) {
                UserUploadImageTaskMark taskMark = imContext.getBusinessModule().getTaskMarkPool().getUserUploadImageTaskMark();
                imContext.getBusinessModule().getServiceWrapper().userUploadImage(this, taskMark, mSharedPrefManager.getUserId(), userImageUrl);
            }
        }
    }

    @Override
    public void onDestroy() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
            FileUtil.delAllChildrenFiles(imgDir);
        }
        super.onDestroy();
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        if (exception == null) {
            if (taskMark instanceof EditUserProfileTaskMark)  {
                mUsernameInput.setText("");
                mPhoneInput.setText("");
                mEmailInput.setText("");
                setViews();
                Toast.makeText(this, R.string.profile_edit_success, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, exception.getExMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
		    /* 从相机获取头像 */
            case R.id.btn_take_photo:
                mSelectPicDialog.dismiss();
                String state = Environment.getExternalStorageState();
                if (state.equals(Environment.MEDIA_MOUNTED)) {
                    String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
                    File dir = new File(imgDir);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    mLocalFilePath = imgDir + System.currentTimeMillis() + ".jpg";
                    Crop.cameraImage(this, Crop.REQUEST_CAMERA, Uri.fromFile(new File(mLocalFilePath)));

                } else {
                    Toast.makeText(this, R.string.check_sdcard, Toast.LENGTH_SHORT).show();
                }

                break;

		    /* 从相册获取图片 */
            case R.id.btn_pick_photo:
                String imgDir = FileUtil.getSdcardStoreDir() + File.separator + PhoConstants.ADD_POST_IMAGE_DIR;
                File dir = new File(imgDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                mSelectPicDialog.dismiss();
                Crop.pickImage(this, Crop.REQUEST_PICK);

                break;

            /* Logout */
            case R.id.sure:
                mLogoutDialog.dismiss();
                ((MainApplication) getApplication()).clearUserCacheNoGoLogin();
                finish();
                break;
        }
    }
}
